package com.sky.service.impl.user;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.user.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.server.WebSocketServer;
import com.sky.service.user.OrderService;
import com.sky.utils.BaiDuMapUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.Alias;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.net.http.HttpResponse;
import java.time.LocalDateTime;
import java.util.*;


@Service
@Slf4j
@Alias("userOrderServiceImpl")
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private BaiDuMapUtil baiDuMapUtil;

    @Override
    @Transactional
    public Result<OrderSubmitVO> submitOrder(OrdersSubmitDTO dto) {
        //  排除异常情况
        // 获取提交订单用户id
        Long userId = BaseContext.getCurrentId();

        BaseContext.removeCurrentId();
        // 判断用户购物车内是否有商品
        List<ShoppingCart> shoppingCartItems = shoppingCartMapper.getShoppingCartItems(userId);
        // 为空 返回失败结果
        if (shoppingCartItems == null || shoppingCartItems.isEmpty())
            return Result.error(MessageConstant.SHOPPING_CART_IS_NULL);
        // 判断地址数据是否正确可查
        AddressBook orderAddress = addressBookMapper.getById(dto.getAddressBookId());
        // 为空 返回失败结果
        if (orderAddress == null)
            return Result.error(MessageConstant.ADDRESS_BOOK_IS_NULL);

        // todo 调用百度接口判断用户地址是否超过商铺地址5公里
        StringBuffer userAddress = new StringBuffer();
        userAddress
                .append(orderAddress.getProvinceName())
                .append(orderAddress.getCityName())
                .append(orderAddress.getDistrictName())
                .append(orderAddress.getDetail());
        try {
            baiDuMapUtil.checkOutOfRange(userAddress.toString());
        } catch (OrderBusinessException e) {
            e.printStackTrace();
//            throw new OrderBusinessException("地址超出配送范围");
            return Result.error("地址超出配送范围");
        }

        // 2.插入主表数据
        // 2.1 封装插入数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);

        // 设置订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        // 刚下单 状态为待付款
        orders.setStatus(Orders.PENDING_PAYMENT);
        // 刚下单 支付状态为未付款
        orders.setPayStatus(Orders.UN_PAID);
        // 下单时间
        orders.setOrderTime(LocalDateTime.now());

        // 设置该订单用户信息
        orders.setUserId(userId);
        orders.setPhone(orderAddress.getPhone());
        orders.setConsignee(orderAddress.getConsignee());
        orders.setAddress(orderAddress.getDetail());
        orders.setUserName(orderAddress.getConsignee());

        // 插入订单数据
        orderMapper.insert(orders);

        // 封装从表数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        shoppingCartItems.forEach(e -> {
            // 将用户购物车内的数据写入订单情况
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(e, orderDetail);
            orderDetail.setId(null);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });

        // 批量往从表中插入订单详情数据
        orderDetailMapper.insertByList(orderDetailList);
        // 清空购物车
        shoppingCartMapper.cleanShoppingCart(userId);

        // 封装vo数据
        OrderSubmitVO submitVO = OrderSubmitVO
                .builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();

        // 返回数据
        return Result.success(submitVO);

    }

    @Override
    @Cacheable(cacheNames = "orderHistory", key = "#userId")
    public Result<PageResult> getUserOrderHistory(OrdersPageQueryDTO dto, Long userId) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);

        // 根据用户id动态判断status查询对应订单记录
        orders.setUserId(userId);

        // 设置分页参数
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        List<Orders> ordersList = orderMapper.getAllOrderInfoByUserIdAndStatus(orders);

        PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);

        // 获取带分页的历史订单数据
        List<Orders> pageInfoList = pageInfo.getList();
        // 查询订单关联详情数据
        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetailsByOrders(pageInfoList);

        // 为每一个历史订单设置对应的订单详情
        pageInfoList.forEach(item -> {
            List<OrderDetail> list = new ArrayList<>();
            orderDetailList.forEach(detail -> {
                if (detail.getOrderId().equals(item.getId())) {
                    list.add(detail);
                }
            });
            item.setOrderDetailList(list);
        });

        // 返回数据
        return Result.success(new PageResult(pageInfo.getTotal(), pageInfoList));

    }

    @Override
    public Result<Orders> getOrderHistoryDetailById(Long id) {
        // 根据订单id查询对应的订单信息
        Orders orders = orderMapper.getOrderInfoById(id);

        // 查询订单对应用户地址信息
        AddressBook ordersAddress = addressBookMapper.getById(orders.getAddressBookId());
        orders.setPhone(ordersAddress.getPhone());
        orders.setConsignee(ordersAddress.getConsignee());
        orders.setAddress(ordersAddress.getDetail());

        // 获取该订单对应的详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetailByOrder(orders);

        orders.setOrderDetailList(orderDetailList);

        return Result.success(orders);
    }

    @Override
    @Transactional
    public Result<Object> cancelOrder(Long id) {
        LambdaUpdateWrapper<Orders> wrapper = new LambdaUpdateWrapper<>();
        wrapper
                .set(Orders::getStatus, Orders.CANCELLED)
                .set(Orders::getCancelTime, LocalDateTime.now())
                .set(Orders::getCancelReason, "用户主动取消")
                .eq(Orders::getId, id);

        orderMapper.update(null, wrapper);

        return Result.success();

    }

    @Override
    @Transactional
    public Result<Object> repetitionOrderById(Long id) {
        // 根据订单id查询该订单历史数据
        Orders historyOrders = orderMapper.getOrderInfoById(id);

        // 二次下单，拷贝相同数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(historyOrders, orders);

        orders.setId(null);
        // 修改下单时间
        orders.setOrderTime(LocalDateTime.now());
        // 修改订单状态和支付状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        // 修改默认送达时间 当前时间加一小时
        orders.setEstimatedDeliveryTime(LocalDateTime.now().plusHours(1));

        // 插入再次下单订单数据
        orderMapper.insert(orders);

        // 获取历史订单对应订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetailByOrder(historyOrders);
        orderDetailList.forEach(e -> {
            // 重新回写关联外键
            e.setOrderId(orders.getId());
        });

        //  插入订单对应订单详情
        orderDetailMapper.insertByList(orderDetailList);

        return Result.success();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        // 使用 webSocket 向客户端发送来单提醒
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId()); // 订单id
        map.put("content", "订单号：" + outTradeNo);
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = null;
        try {
            jsonObject = weChatPayUtil.pay(
                    ordersPaymentDTO.getOrderNumber(), //商户订单号
                    new BigDecimal(0.01), //支付金额，单位 元
                    "苍穹外卖订单", //商品描述
                    user.getOpenid() //微信用户的openid
            );
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new BaseException("调用微信支付接口异常");
        }

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }


    @Override
    public void reminderOrderById(Long id) {
        Orders orders = orderMapper.getOrderInfoById(id);
        //- 通过WebSocket实现管理端页面和服务端保持长连接状态
        //- 当客户支付后，调用WebSocket的相关API实现服务端向客户端推送消息
        //- 客户端浏览器解析服务端推送的消息，判断是来单提醒还是客户催单，进行相应的消息提示和语音播报
        //- 约定服务端发送给客户端浏览器的数据格式为JSON，字段包括：type，orderId，content
        //  - type 为消息类型，1为来单提醒 2为客户催单
        //  - orderId 为订单id
        //  - content 为消息内容
        Map<Object, Object> map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", orders.getId());
        map.put("content", orders.getNumber());

        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }

}
